﻿using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using Imps.Client;
using Imps.Client.Base;
using Imps.Client.CommLayer;
using Imps.Client.Core;
using Imps.Client.Pc;
//using Imps.Client.Resource;
using Imps.Client.Utils;
using Imps.Utils;
using com.hetaoos.FetionSDK.Account;
using com.hetaoos.FetionSDK.Message;
using com.hetaoos.FetionSDK.Event;

namespace com.hetaoos.FetionSDK
{

    public partial class FetionSDK : IFrameworkWindow
    {
        private IUserAccountManager _mgrAccount;
        private ConversationControl _mgrConversation;

        public ConversationControl ConversationControl
        {
            get { return _mgrConversation; }
        }
        private IPersistentManager _mgrPersistent;
        private IUnifiedMessageBox _unifiedMessageBox;
        private static readonly int[] UserError;
        private ContactBase _contactBase;

        #region 没有用的

        //public bool _disableHotKey;
        //private string _mainAppPath;
        //private Imps.Client.Pc.SystemMessageManager _mgrSysMsg;
        //private object _syncObjSensor;
        private IContactManager _mgrContact;
        private IPersonalGroupManager _mgrPersonalGroup;

        public event EventHandler BeginSuspend;

        public event EventHandler MainWindowLoaded;

        public event EventHandler SuspendRestored;
        #endregion

        
        public delegate void SDK_ErrorEventHandler(object sender, SDK_ErrorEventArgs fe);
        public event SDK_ErrorEventHandler SDK_Error;

        public void doSDK_Error(object sender, ErrorType et, Exception Message)
        {
            SDK_ErrorEventArgs msg = new SDK_ErrorEventArgs(et, Message);
            if (SDK_Error != null)
            {
                SDK_Error(sender, msg);
            }
        }

        public void doSDK_Error(object sender,ErrorType et, string Message)
        {
            SDK_ErrorEventArgs msg = new SDK_ErrorEventArgs(et, Message);
            if (SDK_Error != null)
            {
                SDK_Error(sender, msg);
            }
        }

        public delegate void SDK_ReceiveMessageEventHandler(object sender, SDK_ReceiveMessageEventArgs fe);
        public event SDK_ReceiveMessageEventHandler SDK_ReceiveMessage;

        public void doSDK_ReceiveMessage(object sender,Conversation conv, Contact contact, string message)
        {
            SDK_ReceiveMessageEventArgs msg = new SDK_ReceiveMessageEventArgs(conv, contact, message);
            if (SDK_ReceiveMessage != null)
            {
                SDK_ReceiveMessage(sender, msg);
            }
        }
        //public event SDK_ReceiveMessageArgs SDK_ReceiveMessage;

        public delegate void SDK_UserSatusChangedEventHandler(object sender, Imps.Client.Core.UserSatusChangedEventArgs e);
        public event SDK_UserSatusChangedEventHandler SDK_UserSatusChange;

        static FetionSDK()
        {
            int[] numArray = new int[3];
            numArray[1] = 0x579;
            numArray[2] = 0x57c;
            UserError = numArray;
        }

        public FetionSDK()
            : this(new string[0])
        {
        }

        public FetionSDK(string[] args)
        {
            //this.components = new Container();
            Control.CheckForIllegalCrossThreadCalls = false;
            try
            {
                this.HandleExceptions();
                this.InitUiComponents();
                this.DoAfterLoaded(this, null);
            }
            catch (Exception exception)
            {
                //-DEBUGMessageBox.Show(exception.Message);
            }
        }


        private void ConversationManager_ReceiveSystemMessage(object sender, ImpsNotifyEventArgs e)
        {
            UiErrorHelper.HandEventSafely(this, delegate
            {
                string xml = e.Text;
                XmlDocument document = new XmlDocument();
                try
                {
                    document.LoadXml(xml);
                }
                catch
                {
                    return;
                }
                XmlElement documentElement = document.DocumentElement;
                if ((documentElement != null) && (documentElement.Name == "msg"))
                {
                    string str2 = XmlHelper.ReadXmlAttributeString(documentElement, "id");
                    if (!string.IsNullOrEmpty(str2))
                    {
                        XmlElement nextSibling = (XmlElement)documentElement.FirstChild;
                        if ((nextSibling != null) && (nextSibling.Name == "validity"))
                        {
                            string str3 = XmlHelper.ReadXmlAttributeString(nextSibling, "end");
                            if (!string.IsNullOrEmpty(str3))
                            {
                                nextSibling = (XmlElement)nextSibling.NextSibling;
                                if ((nextSibling != null) && (nextSibling.Name == "content"))
                                {
                                    string content = nextSibling.InnerText;
                                    nextSibling = (XmlElement)nextSibling.NextSibling;
                                    string link = "";
                                    if (nextSibling != null)
                                    {
                                        link = nextSibling.InnerText;
                                    }
                                    //SystemMessage msg = new SystemMessage(str2, link, link, str3);
                                    //this._mgrSysMsg.AddSystemMessage(msg);
                                }
                            }
                        }
                    }
                }
            });
        }

        private void CurrentUser_ExServicesStatusChanged(object sender, ExServiceEventArgs e)
        {
        }

        private void CurrentUser_ImpsError(object sender, ImpsErrorEventArgs e)
        {
            if (Array.IndexOf<int>(UserError, e.ErrorCode) >= 0)
            {
                //UiErrorHelper.ShowImpsError(this, this, e);
            }
        }

        private void CurrentUser_StatusChanged(object sender, UserSatusChangedEventArgs e)
        {
            if (SDK_UserSatusChange != null)
            {
                SDK_UserSatusChange(sender, e);
            }
            if(true)
            {
                return;
            }

            try
            {
                //-DEBUGMessageBox.Show(DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToLongTimeString() + ":\n\t" + e.NewStatus.ToString());
                switch (e.NewStatus)
                {
                    case UserAccountStatus.None:
                    case UserAccountStatus.Disconnected:
                        goto Label_008A;

                    case UserAccountStatus.Initialized:
                    case UserAccountStatus.WaitReconnect:
                    case UserAccountStatus.StandBy:
                        return;

                    case UserAccountStatus.Loginning:
                    case UserAccountStatus.Logouting:
                    case UserAccountStatus.Logoff:
                        this.InnerCloseChildWindows();
                        if (e.NewStatus == UserAccountStatus.Logoff)
                        {
                            goto Label_008A;
                        }
                        return;

                    case UserAccountStatus.Logon:
                        break;

                    case UserAccountStatus.OfflineLogon:
                        break;

                    default:
                        return;
                }

                return;
            Label_008A:
                EnvHelper.StressMemory();
            }
            catch (Exception exception)
            {
                UiErrorHelper.HandExceptionSafely(this, exception);
            }
        }

        private void DoAfterLoaded(object sender, EventArgs e)
        {
            try
            {
                GlobalTimer.Unregister(new EventHandler(this.DoAfterLoaded));
                if (!ConnectionFactory.HasRegisteredConnectionManager())
                {
                    IConnectionManager manager = new ConnectionManagerImp(this.CurrentUser);
                    ConnectionFactory.RegisterConnectionManager(manager);
                }
            }
            catch (Exception exception)
            {
                UiErrorHelper.HandExceptionSafely(this, exception);

            }
        }

        public IUserAccountManager AccountManager
        {
            get
            {
                return this._mgrAccount;
            }
        }

        public ContactBase ContactControl
        {
            get { return _contactBase; }
        }

        public IConversationManager ConversationManager
        {
            get
            {
                if (this._mgrConversation == null)
                {
                    this._mgrConversation = new com.hetaoos.FetionSDK.Message.ConversationControl(this);
                }
                return this._mgrConversation;
            }
        }

        internal Imps.Client.Core.User CurrentUser
        {
            get
            {
                if (this._mgrAccount == null)
                {
                    return null;
                }
                return this._mgrAccount.CurrentUser;
            }
        }

        #region 没有实现的或者没有用的

        public void ShowAbout(IWin32Window owner)
        {
        }

        public DialogResult ShowOptions(string name)
        {
            return this.ShowOptions(null, name);
        }

        public DialogResult ShowOptions(IWin32Window owner, string name)
        {
            //-DEBUGMessageBox.Show(owner, name);
            return DialogResult.OK;
        }

        public void ShowEntryPoint()
        {
        }
        public void ActiveMainWindow()
        {

        }

        private void InnerCloseChildWindows()
        {
            //throw new NotImplementedException();
        }
        private void HandleExceptions()
        {
        }

        public void HideMainWindow()
        {
        }

        private void InitUiComponents()
        {
            this._mgrPersistent = new Imps.Client.Pc.PersistentManager(this);
            this._mgrAccount = new UserAccountManager(this);
            this.CurrentUser.StatusChanged += new EventHandler<UserSatusChangedEventArgs>(this.CurrentUser_StatusChanged);
            this.CurrentUser.ImpsError += new EventHandler<ImpsErrorEventArgs>(this.CurrentUser_ImpsError);
            //this._mgrContact = new Imps.Client.Pc.ContactManager(this);
            this.CurrentUser.ExServicesStatusChanged += new EventHandler<ExServiceEventArgs>(this.CurrentUser_ExServicesStatusChanged);
            //this._mgrSysMsg = new Imps.Client.Pc.SystemMessageManager(this);
            this.AccountManager.CurrentUser.ConversationManager.ReceiveSystemMessage += new EventHandler<ImpsNotifyEventArgs>(this.ConversationManager_ReceiveSystemMessage);
            _contactBase = new ContactBase(this);

            try
            {
                if (this._mgrConversation == null)
                {
                    this._mgrConversation = new com.hetaoos.FetionSDK.Message.ConversationControl(this);
                }
                if (this._mgrPersonalGroup == null)
                {
                    //this._mgrPersonalGroup = new Imps.Client.Pc.PersonalGroupManager(this);
                }
            }
            catch (Exception exception)
            {
                ClientLogger.WriteException(exception);
            }
        }

        public bool NavigateToTab(string tabName, string args)
        {
            return true;
        }

        private void ShowUserInfo()
        {
        }
        public IContainer ComponentContainer
        {
            get
            {
                return new Container();
            }
        }

        public IContactManager ContactManager
        {
            get
            {
                return this._mgrContact;
            }
        }
        public IImportExportManager ImportExportManager
        {
            get
            {
                return null;
            }
        }

        public IIVRManager IVRManager
        {
            get
            {
                return null;
            }
        }

        public string MainAppPath
        {
            get
            {
                return Path.Combine(FilePathHelper.AppBaseDir, "FetionSDK.dll");
            }
        }

        public Form MainWindow
        {
            get
            {
                return null;
            }
        }

        public IMessageHistoryManager MessageHistoryManager
        {
            get
            {
                return null;
            }
        }

        public IPersistentManager PersistentManager
        {
            get
            {
                return this._mgrPersistent;
            }
        }

        public IPersonalGroupManager PersonalGroupManager
        {
            get
            {
                return null;
            }
        }

        private Size RestoredSize
        {
            get
            {
                return new Size();
            }
        }

        public IUnifiedMessageBox UnifiedMessageBox
        {
            get
            {
                if (this._unifiedMessageBox == null)
                {
                    this._unifiedMessageBox = new Imps.Client.Pc.UnifiedMessageBox(this);
                }
                return this._unifiedMessageBox;
            }
        }

        #endregion


        //private void btnLogin_Click(object sender, EventArgs e)
        //{
        //    _mgrAccount.FillUserIdAndPassword(cmbId.Text, tbPassword.Text, false);
        //    _mgrAccount.LoginOrLogout();
        //}

        //private void button2_Click(object sender, EventArgs e)
        //{
        //    _contactBase.SendSMS.SendSMS("13768432170", "This is a Test");
        //}

        //private void button3_Click(object sender, EventArgs e)
        //{
        //    //15877029295
        //    //_contactBase.SendSMS.s
        //    //selectedContacts[0].Uri.Raw
        //    Contact friend = _contactBase.findContact("15877029295");
        //    if (friend != null)
        //    {
        //        //ConversationManager.StartConversation(this, ConversationOperation.SmsChat, new string[] { friend.Uri.Raw });
        //    }
        //    else
        //    {
        //        MessageBox.Show("用户为空");
        //    }
        //}
        //private void button1_Click(object sender, EventArgs e)
        //{

        //    string text = string.Empty;
        //    foreach (Contact contact in this._contactBase.getAllContactList())
        //    {
        //        string str2 = text;
        //        text = str2 + contact.DisplayName + ":" + contact.Uri.Id + ":" + contact.PersonalInfo.MobileNo + "\n";
        //    }
        //    MessageBox.Show(text);
        //}

    }
}

